package com.wangye.mp;

import com.wangye.commom.EmptyUtil;
import com.wangye.mp.constant.MPConstantUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by 王叶 on 2018/3/15.
 * 微信公众平台 （Media Platform） 配置
 */
public class MPConfig {

    private static Logger logger = LoggerFactory.getLogger("mpconsole");

    private static Properties properties;

    /**
     * 微信公众平台
     */
    private static String APPID ;               //开发者ID
     private static String APPSECRET;           //开发者密码
     private static String WEIXIN_TOKEN;        //服务器配置 令牌(Token)
     private static String WEIXIN_URL;          //服务Url

    static {
        // 先读取 jar 包外 配置文件 mp.properties
        properties = new Properties();
        InputStream in;
        String filePath = System.getProperty("user.dir")+ File.separator + "conf"+ File.separator + "mp.properties";
        try {
//            in = new BufferedInputStream(new FileInputStream(filePath));      //读取包外配置文件
            in = MPConfig.class.getClassLoader().getResourceAsStream(File.separator + "conf" + File.separator + "mp.properties");   //读取包类配置文件
            properties.load(in);
            APPID = properties.getProperty("mp.AppID");
            if (EmptyUtil.isEmpty(APPID)) {
                throwExceptionInInitializerError("mp.AppID 不能为空");
            }

            APPSECRET = properties.getProperty("mp.AppSecret");
            if (EmptyUtil.isEmpty(APPSECRET)) {
                throwExceptionInInitializerError("mp.AppSecret 不能为空");
            }

            WEIXIN_TOKEN = properties.getProperty("mp.Token");
            if (EmptyUtil.isEmpty(WEIXIN_TOKEN)) {
                throwExceptionInInitializerError("mp.Token 不能为空");
            }

            WEIXIN_URL = properties.getProperty("mp.serverUrl", MPConstantUtil.DEFAULT_WEIXIN_URL);
            if (EmptyUtil.isEmpty(WEIXIN_URL)) {
                throwExceptionInInitializerError("mp.WEIXIN_URL 不能为空");
            }
        } catch (FileNotFoundException e) {
            logger.info("未找到配置文件 "+File.separator+"conf"+File.separator+"mp.properties");
            throwExceptionInInitializerError("未找到");
            e.printStackTrace();
            //外部配置文件未找到

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void throwExceptionInInitializerError(String message) {
        throw new ExceptionInInitializerError(File.separator+"conf"+File.separator+"mp.properties 配置文件！" +message);
    }

    public static String getAPPID() {
        return APPID;
    }

    public static String getAPPSECRET() {
        return APPSECRET;
    }

    public static String getWeixinToken() {
        return WEIXIN_TOKEN;
    }

    public static String getWeixinUrl() {
        return WEIXIN_URL;
    }
}
